package com.shxc.smarttrade.quotation.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.shxc.smarttrade.R;
import com.shxc.smarttrade.base.BaseActivity;
import com.shxc.smarttrade.currency.model.CurrencyModel;
import com.shxc.smarttrade.info.Contents;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisModel;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisUtils;
import com.shxc.smarttrade.quotation.adapter.QuotationChoosePagerAdapter;
import com.shxc.smarttrade.quotation.adapter.QuotatonChooseBottomAdapter;
import com.shxc.smarttrade.quotation.adapter.QuotatonChooseTopAdapter;
import com.shxc.smarttrade.quotation.model.BriefModel;
import com.shxc.smarttrade.quotation.model.TradeCategory;
import com.shxc.smarttrade.utils.Loger;
import com.shxc.smarttrade.utils.MyOkHttpUtils;
import com.shxc.smarttrade.utils.ToastUtils;
import com.shxc.smarttrade.utils.UiUtils;

import org.xchris.view.annotation.ContentView;
import org.xchris.view.annotation.Event;
import org.xchris.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 行情 - 自选
 */
@ContentView(R.layout.activity_quotation_choose)
public class QuotationChooseActivity extends BaseActivity {

    @ViewInject(R.id.left_imageview)
    ImageView left_imageview;//回退
    @ViewInject(R.id.title_textview)
    TextView title_textview;//标题
    @ViewInject(R.id.right_textview)
    TextView right_textview;//右边完成
    @ViewInject(R.id.note_textview)
    TextView note_textview;//左提示
    @ViewInject(R.id.prompt_textview)
    TextView prompt_textview;//右提醒
    @ViewInject(R.id.top_recyclerview)
    RecyclerView top_recyclerview;//上方选择列表
    @ViewInject(R.id.tablayout)
    TabLayout tablayout;//
    @ViewInject(R.id.viewpager)
    ViewPager viewpager;//下方滑动窗口

    private List<BriefModel> list;//自选

    private List<TradeCategory.DataBean.SymbolsBean> list0;//0 外汇；
    private List<TradeCategory.DataBean.SymbolsBean> list1;//1 指数；
    private List<TradeCategory.DataBean.SymbolsBean> list2;//2 贵金属；
    private List<TradeCategory.DataBean.SymbolsBean> list3;//3 能源,

    private QuotatonChooseBottomAdapter adapter0;
    private QuotatonChooseBottomAdapter adapter1;
    private QuotatonChooseBottomAdapter adapter2;
    private QuotatonChooseBottomAdapter adapter3;

    private QuotatonChooseTopAdapter topAdapter;

    private static final String[] tabName = {"货币", "商品", "能源", "指数"};
    private List<String> tabTitleList = Arrays.asList(tabName);

    private QuotationChoosePagerAdapter pagerAdapter;

    private String symbol = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        list0 = new ArrayList();//0 外汇；
        list1 = new ArrayList();//1 指数；
        list2 = new ArrayList();//2 贵金属；
        list3 = new ArrayList();//3 能源,

        left_imageview.setVisibility(View.VISIBLE);
        title_textview.setText("编辑自选");
        right_textview.setVisibility(View.VISIBLE);
        right_textview.setText("完成");

        Bundle bundle = getIntent().getExtras();
        list = (List<BriefModel>) bundle.get("list");
        Loger.e("list.size", list.size());

        initRecycler();
        initViewPager();
        getAllSymbol();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Event({R.id.left_imageview, R.id.right_textview})
    private void onClick(View view) {

        switch (view.getId()) {
            case R.id.left_imageview:
                //关闭
                finish();
                break;
            case R.id.right_textview:
                list = topAdapter.getList();
                if (list.size() == 1 && list.get(0).getSymbolEn().equals("")) {
                    symbol = "";
                } else {
                    for (int i = 0; i < list.size(); i++) {
                        if (i == 0) {
                            symbol = list.get(i).getSymbolEn();
                        } else {
                            symbol = symbol + "," + list.get(i).getSymbolEn();
                        }
                    }
                }
                diySymbol();
                break;
        }
    }

    String group = "";
    int position = -1;

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    //从列表中删除关注项目
                    BriefModel briefModel = (BriefModel) msg.obj;
                    switch (briefModel.getGroup()) {
                        case "0":
                            adapter0.setModelForse(briefModel.getSymbolEn());
                            break;
                        case "1":
                            adapter1.setModelForse(briefModel.getSymbolEn());
                            break;
                        case "2":
                            adapter2.setModelForse(briefModel.getSymbolEn());
                            break;
                        case "3":
                            adapter3.setModelForse(briefModel.getSymbolEn());
                            break;
                    }
                    list = topAdapter.getList();
                    adapter0.setNums(list.size());
                    adapter1.setNums(list.size());
                    adapter2.setNums(list.size());
                    adapter3.setNums(list.size());
                    ifListNull();
                    break;
                case 2:
                    //从下方列表向上添加关注项目
                    TradeCategory.DataBean.SymbolsBean tds = (TradeCategory.DataBean.SymbolsBean) msg.obj;
                    BriefModel bm = new BriefModel(tds.getSymbolEn(), tds.getSymbolCn(), tds.getGroup());
                    position = msg.arg1;
                    Loger.e("position - ac", position);
                    group = tds.getGroup();
                    topAdapter.addModel(bm);
                    list = topAdapter.getList();
                    adapter0.setNums(list.size());
                    adapter1.setNums(list.size());
                    adapter2.setNums(list.size());
                    adapter3.setNums(list.size());
                    break;
                case 3:
                    //自选超过15个
                    ToastUtils.showToast("您最多只可以添加15个自选项目");
                    break;
            }
            super.dispatchMessage(msg);
        }
    };

    /**
     * 选中品种为空
     * */
    private void ifListNull() {
        if (list == null || list.size() == 0) {
            list = new ArrayList<>();
            BriefModel briefModel = new BriefModel("", "", "");
            list.add(briefModel);
            topAdapter.setNullList(list);
            note_textview.setText("选择下方您感兴趣的品种");
            prompt_textview.setVisibility(View.INVISIBLE);
        } else {
            note_textview.setText("我的自选");
            prompt_textview.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 初始化recyclerview
     * */
    private void initRecycler() {
        if (list == null || list.size() == 0) {
            list = new ArrayList<>();
            BriefModel briefModel = new BriefModel("", "", "");
            list.add(briefModel);
        }
        topAdapter = new QuotatonChooseTopAdapter(mContext, list, handler);
        top_recyclerview.setLayoutManager(new GridLayoutManager(mContext, 3) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }//不可滑动
        });
        top_recyclerview.setAdapter(topAdapter);
        top_recyclerview.setItemAnimator(new DefaultItemAnimator());

        //为RecycleView绑定触摸事件
        ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                //首先回调的方法 返回int表示是否监听该方向
//                int dragFlags = ItemTouchHelper.UP|ItemTouchHelper.DOWN;//拖拽
//                int swipeFlags = ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT;//侧滑删除
//                return makeMovementFlags(dragFlags,swipeFlags);
                int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;//拖拽
//                int swipeFlags = ItemTouchHelper.
                return makeMovementFlags(dragFlags, 0);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                //滑动事件
                Collections.swap(list, viewHolder.getAdapterPosition(), target.getAdapterPosition());
                topAdapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
                return false;

                //首先回调的方法 返回int表示是否监听该方向
//                int dragFlags = ItemTouchHelper.UP|ItemTouchHelper.DOWN|ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT;//拖拽
//                int swipeFlags = 0;//侧滑删除
//                return makeMovementFlags(dragFlags,swipeFlags);
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                //侧滑事件
//                list.remove(viewHolder.getAdapterPosition());
//                adapter.notifyItemRemoved(viewHolder.getAdapterPosition());

            }

            @Override
            public boolean isLongPressDragEnabled() {
                //是否可拖拽
                return true;
            }
        });
        helper.attachToRecyclerView(top_recyclerview);
    }

    /**
     * 初始化viewpager
     * */
    private void initViewPager() {
        viewpager.setOffscreenPageLimit(4);
        adapter0 = new QuotatonChooseBottomAdapter(mContext, list0, handler);
        adapter1 = new QuotatonChooseBottomAdapter(mContext, list1, handler);
        adapter2 = new QuotatonChooseBottomAdapter(mContext, list2, handler);
        adapter3 = new QuotatonChooseBottomAdapter(mContext, list3, handler);

        pagerAdapter = new QuotationChoosePagerAdapter(LayoutInflater.from(mContext), mContext, tabTitleList,
                adapter0, adapter1, adapter2, adapter3);
        viewpager.setAdapter(pagerAdapter);

        tablayout.setupWithViewPager(viewpager);
        tablayout.post(new Runnable() {
            @Override
            public void run() {
                UiUtils.setTabLineWidth(tablayout,20);//字线同宽
            }
        });
    }

    //所有品种的当前行情
    public void getAllSymbol() {
        loadingDialog.show();
        Map<String, Object> map = new HashMap<>();
        map.put("userId", spImp.getUserId());

        MyOkHttpUtils.getServiceDatas(map, Contents.DEAL_SYMBOL_LIST, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, TradeCategory.class);
                    if (jam.isSuccess()) {
                        TradeCategory model = (TradeCategory) jam.getData();
                        for (int i = 0; i < model.getData().getSymbols().size(); i++) {
                            TradeCategory.DataBean.SymbolsBean symbolsBean = model.getData().getSymbols().get(i);
                            switch (symbolsBean.getGroup()) {
                                case "0":
                                    list0.add(symbolsBean);
                                    break;
                                case "1":
                                    list1.add(symbolsBean);
                                    break;
                                case "2":
                                    list2.add(symbolsBean);
                                    break;
                                case "3":
                                    list3.add(symbolsBean);
                                    break;
                            }
                        }
                        for (int i = 0; i < list0.size(); i++) {
                            list0.get(i).setPosition(i);
                        }
                        for (int i = 0; i < list1.size(); i++) {
                            list1.get(i).setPosition(i);
                        }
                        for (int i = 0; i < list2.size(); i++) {
                            list2.get(i).setPosition(i);
                        }
                        for (int i = 0; i < list3.size(); i++) {
                            list3.get(i).setPosition(i);
                        }
                        adapter0.setList(list0);
                        adapter1.setList(list1);
                        adapter2.setList(list2);
                        adapter3.setList(list3);
                        adapter0.setNums(list.size());
                        adapter1.setNums(list.size());
                        adapter2.setNums(list.size());
                        adapter3.setNums(list.size());

                    } else {
                        Loger.e("tc", jam.getMsg());
                    }
                }
                loadingDialog.dismiss();
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
            }
        });
    }

    //对用户关注品种进行添加,删除,排序操作
    public void diySymbol() {
        loadingDialog.show();
        Map<String, Object> map = new HashMap<>();
        map.put("userId", spImp.getUserId());
        map.put("symbol", symbol);

        MyOkHttpUtils.getServiceDatas(map, Contents.DEAL_SYMBOL_DIYSYMBOL, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, CurrencyModel.class);
                    if (jam.isSuccess()) {
                        ToastUtils.showToast("自选操作成功");
                        finish();
                    } else {
                        ToastUtils.showToast(jam.getMsg());
                    }
                }
                loadingDialog.dismiss();
            }
            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
            }
        });
    }

}
